package cn.com.dycc.task_manage.ordermain.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.party_org.organize.service.NotFoundOrganizeException;
import cn.com.dycc.task_manage.orderdeal.dao.OrderDealDao;
import cn.com.dycc.task_manage.orderdeal.entity.OrderDealEntity;
import cn.com.dycc.task_manage.orderdeal.param.OrderDealParam;
import cn.com.dycc.task_manage.orderdeal.service.NotFoundOrderDealException;
import cn.com.dycc.task_manage.ordermain.dao.OrderMainDao;
import cn.com.dycc.task_manage.ordermain.entity.OrderMainEntity;
import cn.com.dycc.task_manage.ordermain.entity.ResultOrderMain;
import cn.com.dycc.task_manage.ordermain.entity.UserOrderEntity;
import cn.com.dycc.task_manage.ordermain.param.FindAllParam;
import cn.com.dycc.task_manage.ordermain.param.OrderMainParam;
import cn.com.dycc.task_manage.ordermain.param.SendingListsParam;
import cn.com.dycc.util.AttachUtil;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.FileUtil;
import cn.com.dycc.util.IntegerUtil;
import cn.com.dycc.util.Paging;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 工单待办业务处理层
 * @author linfa
 *
 */
@Service("orderMainService")
@Transactional(rollbackFor=Exception.class)
public class OrderMainServiceImpl implements OrderMainService{
	
	@Resource(name="orderMainDao")
	private OrderMainDao orderMainDao;
	
	@Resource(name="orderDealDao")
	private OrderDealDao orderDealDao;
	
	@Resource(name="attachDao")
	private AttachDao attachDao;
	
	@Resource(name="paging")
	private Paging paging;
	
	//发送工单任务
	@SystemServiceLog(description=Constants.ORDER_ADD)
	public String sendOrderMain(HttpServletRequest request, SendingListsParam sendingListsParam)
			throws NotFoundOrderMainException {
		
		//工单属性
		OrderMainParam orderMainParam = sendingListsParam.getOrderMainParam();
		List<OrderDealParam> listOrderDealParam = sendingListsParam.getListOrderDealParam();
		
		if(orderMainParam==null){
			throw new NotFoundOrderMainException("请填写内容！");
		}
		
		if(listOrderDealParam.size()==0){
			throw new NotFoundOrderMainException("请选择处理人！");
		}
		
		if(orderMainParam.getOrder_title()==null||orderMainParam.getOrder_title().trim().isEmpty()){
			throw new NotFoundOrderMainException("请填写标题！");
		}
		
		if(orderMainParam.getOrder_type()==null||orderMainParam.getOrder_type().trim().isEmpty()){
			throw new NotFoundOrderMainException("请填写类别！");
		}
		
		if(!(IntegerUtil.isNumeric(orderMainParam.getOrder_type()))){
			throw new NotFoundOrderMainException("类别属性为整型！");
		}
		
		if(orderMainParam.getOrder_des()==null||orderMainParam.getOrder_des().trim().isEmpty()){
			throw new NotFoundOrderMainException("请填写内容描述！");
		}
		
		String send_user_id = request.getSession().getAttribute("id").toString();
		if(send_user_id==null){
			throw new NotFoundOrderMainException("请登录！");
		}
		
		String send_dept_no = request.getSession().getAttribute("dept_id").toString();
		if(send_dept_no==null||send_dept_no.trim().isEmpty()){
			throw new NotFoundOrderMainException("您不是党员用户！");
		}
		
		if(orderMainParam.getTask_limit_date()==null||orderMainParam.getTask_limit_date().trim().isEmpty()){
			throw new NotFoundOrderMainException("请选择任务需要完成的时间！");
		}
		
//		if(orderMainParam.getState()==null||orderMainParam.getState().trim().isEmpty()){
//			throw new NotFoundOrderMainException("请填写可用状态！");
//		}
		
		String org_id = request.getSession().getAttribute("org_id").toString();
		//工单状态 1处理中   2完成归档   3取消工单
		String order_status = "1";
		
		//拟单时间
		String format = "yyyy-MM-dd HH:mm:ss";
		String send_date = DateUtil.getNowDate(format);
		orderMainParam.setSend_date(send_date);
		orderMainParam.setSend_dept_id(send_dept_no);
		orderMainParam.setSend_user_id(send_user_id);
		orderMainParam.setOrg_id(org_id);
		orderMainParam.setOrder_status(order_status);
		orderMainParam.setOpt_user_id(send_user_id);
		
		int addMain = orderMainDao.sendOrderMain(orderMainParam);
		if(addMain==0){
			throw new NotFoundOrderMainException("发送失败！");
		}
		
		//返回主表id
		String order_id = orderMainParam.getOrder_id();
		//发起人写入从表，生成pid为0的主干
		String deal_pid = "0";
		String deal_status = "2";  //1处理中   2完成归档   3阅知工单
		OrderDealParam orderDealParam = new OrderDealParam();
		orderDealParam.setOrder_id(order_id);
		orderDealParam.setDeal_pid(deal_pid);
		orderDealParam.setDeal_user_id(send_user_id);
		orderDealParam.setDeal_dept_id(send_dept_no);
		orderDealParam.setRec_time(send_date);
		orderDealParam.setFinish_date(send_date);
		orderDealParam.setOrder_status(deal_status);
		orderDealParam.setOrg_id(org_id);
		orderDealParam.setOpt_user_id(send_user_id);
		orderDealParam.setState("Y");
		int addeal = orderDealDao.recOrderDeal(orderDealParam);
		if(addeal==0){
			throw new NotFoundOrderMainException("发送失败！");
		}
		//返回工单细表id作为下节点的pid
		String deal_id = orderDealParam.getDeal_id();
		
		for(OrderDealParam odp : listOrderDealParam){
			odp.setOrder_id(order_id);
			odp.setDeal_pid(deal_id);
			if(odp.getDeal_user_id()==null||odp.getDeal_user_id().trim().isEmpty()){
				throw new NotFoundOrderMainException("请选择处理人！");
			}
			if(odp.getDeal_dept_id()==null||odp.getDeal_dept_id().trim().isEmpty()){
				throw new NotFoundOrderMainException("请选择处理人部门！");
			}
			
//			System.out.println("ce1="+odp.getTime_limit()==null);
			if(odp.getTime_limit()!=null){
				DateUtil.compare(odp.getTime_limit(),orderMainParam.getTask_limit_date(),format);
			}
			odp.setRec_time(send_date);
			odp.setState("Y");
			odp.setOrder_status(order_status);
			odp.setOpt_user_id(send_user_id);
			odp.setOrg_id(org_id);
		}
		
		int batch = orderDealDao.batchOrderDeal(listOrderDealParam);
		
		if(batch==0){
			throw new NotFoundOrderMainException("发送失败！");
		}
		
		//附件上传
		List<Attach> list = sendingListsParam.getListAttach();
		//将上传的图片流转换为附件字段
		List<Attach> listAttach = new ArrayList<Attach>();
		//附件移到正式文件夹
		List<Attach> newListAttach = new ArrayList<Attach>();
	//	System.out.println("l="+listAttach.size());
        if (list != null&&list.size()!=0) {  
        	JSONArray json=JSONArray.fromObject(list);
 //       	System.out.println("jo="+json.size());
			for(int i=0;i<json.size();i++){
//				System.out.println("打桩1111111111111");
//				System.out.println("打桩2："+json.get(i));
				Object check=json.get(i);
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				
	//			System.out.println("job"+job);
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				Attach attach=new Attach();
				attach.setMessage_no(order_id);
				attach.setAttach_type(Integer.valueOf(AttachUtil.order_main_attach_type));
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id(org_id);
				attach.setOpt_user_id(send_user_id);
				listAttach.add(attach);
//				System.out.println(attach_ext);
//				System.out.println(attach_path);
//				System.out.println(attach_size);
//				System.out.println(title);	
			}
			newListAttach=FileUtil.moveFile(listAttach,"task_manage");
			int addAttach = attachDao.addAttachBatch(newListAttach);
			if(addAttach==0){
				throw new NotFoundOrderMainException("发送失败！");
			}
		}

		return "发送成功！";
	}
	
	//根据order_id查询工单主表信息
	public UserOrderEntity findUserOrderByOrderId(HttpServletRequest request,String order_id) throws NotFoundOrderMainException {
		
		if(order_id==null||order_id.trim().isEmpty()){
			throw new NotFoundOrderMainException("请选择需要查询的工单！");
		}
		
		UserOrderEntity userOrderEntity = new UserOrderEntity();
		String org_id = request.getSession().getAttribute("org_id").toString();
		try {
			OrderMainEntity orderMainEntity = orderMainDao.findOrderMainByOrderId(order_id,org_id);
			List<OrderDealEntity> list = orderDealDao.findOrdealByOrderId(order_id,org_id);
			
			userOrderEntity.setListOrderDealEntity(list);
			userOrderEntity.setOrderMainEntity(orderMainEntity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new NotFoundOrderMainException("查询失败！");
		}
		
		return userOrderEntity;
	}
	
	//根据登录用户查询所有自己发送的工单
	public List<ResultOrderMain> findAll(HttpServletRequest request,FindAllParam findAllParam,String status) throws NotFoundOrderMainException {
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String send_user_id = request.getSession().getAttribute("id").toString();
		if(send_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		Integer limit = findAllParam.getLimit();
		Integer page = findAllParam.getPage();
		
		if(!(IntegerUtil.isNumeric(page.toString()))){
			throw new NotFoundOrganizeException("查询页码为整型！");
		}
		
		Integer start = null;
		if(limit==null&&page!=null){
			limit = paging.getPageSize();
			start=(page-1)*limit;
		}
		if(page==null){
			start = null;
			limit = null;
		}
		if(limit!=null&&page!=null){
			start = limit*(page-1);
		}
		
		if("1".equals(status)){
			findAllParam.setSend_user_id(null);
		}else{
			findAllParam.setSend_user_id(send_user_id);
		}
		
		findAllParam.setOrg_id(org_id);
		findAllParam.setStart(start);
		findAllParam.setLimit(limit);
		
		return orderMainDao.findAll(findAllParam);
	}
	
	//根据登录用户查询所有自己发送的工单 统计
	public String findAllCount(HttpServletRequest request,String status,String order_title) throws NotFoundOrderMainException {
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String send_user_id = null;
		
		if(!("1".equals(status))){
			send_user_id = request.getSession().getAttribute("id").toString();	
		}
		
		return orderMainDao.findAllCount(org_id, send_user_id,order_title);
	}


}
